package com.xiaode.controller.app.task.ordinary;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Redis;
import com.xiaode.common.constant.Const;
import com.xiaode.common.model.Admin;
import com.xiaode.common.model.OrdinaryTask;
import com.xiaode.common.model.OrdinaryUserTask;
import com.xiaode.common.model.StudentTrajectory;
import com.xiaode.common.model.TaskLog;
import com.xiaode.exce.EnumError;
import com.xiaode.util.UserUtil;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class OrdinaryService {

    
    /**
     * 发布任务
     */
    public Ret publishTask(Integer accountId, Integer userTypeMy, String content, String title, String pictures, Integer score) throws Exception {
        if(userTypeMy != Const.UserType.admin) {
        	return Ret.fail().set("error", EnumError.TASK_ONLY_TEACHER.getObj());
        }
    	//保存普通任务
        OrdinaryTask ordinaryTask = new OrdinaryTask();
        ordinaryTask.setContent(content);
        ordinaryTask.setPictures(pictures);
        ordinaryTask.setTitle(title);
        ordinaryTask.setScore(score);
        ordinaryTask.setPublishAccountId(accountId);
        ordinaryTask.save();
        return Ret.ok();
    }
    
    /**
     * 修改任务
     */
    public Ret updateTask(Integer accountId, Integer userTypeMy, Integer taskId, String content, String title, String pictures, Integer score, Boolean isDel) throws Exception {      
    	if(userTypeMy != Const.UserType.admin) {
        	return Ret.fail().set("error", EnumError.TASK_ONLY_TEACHER.getObj());
        }
    	if (StrUtil.isNotEmpty(pictures)) {
            List<String> strings = JSONUtil.toList(pictures, String.class);
            if (strings.size() > 9) {
                return Ret.fail().set("error", EnumError.PIC_TOO_MANY.getObj());
            }
        }
        OrdinaryTask task = OrdinaryTask.dao.findById(taskId);
        if (BeanUtil.isEmpty(task)) {
            return Ret.fail().set("error", EnumError.TASK_NOT_EXIST.getObj());
        }
        task.setPictures(pictures);
        task.setScore(score);
        task.setIsDel(isDel);
        task.update();
        
        return Ret.ok();
    }
    
    /**
     * 查询任务
     * 注：所有学生都可以做任务，但是审核任务是自己的老师审核
     */
    public Ret findTaskPage(Integer accountId, Integer userType, Boolean isMy, Integer page, Integer limit) throws Exception {
    	//如果是老师自己查询我的发布
    	if(isMy && userType == Const.UserType.admin) {
        	Page<OrdinaryTask> taskPage = OrdinaryTask.dao.paginate(page, limit, "SELECT id,title,content,add_time", " FROM ordinary_task WHERE publish_account_id = ? ORDER BY id DESC", accountId);
            return Ret.ok("taskPage", taskPage);
    	}
    	//学生在任务中查看
    	if(userType == Const.UserType.student) {
    		//获取学生的导师和班主任
        	Page<OrdinaryTask> taskPage = OrdinaryTask.dao.paginate(page, limit, "SELECT id,title,content,add_time", " FROM ordinary_task WHERE is_del = 0 ORDER BY id DESC");
        	List<OrdinaryTask> taskList = taskPage.getList();
        	for(OrdinaryTask task : taskList) {
        		//添加自己做的情况
        		OrdinaryUserTask taskUser = OrdinaryUserTask.dao.findFirst("SELECT * FROM ordinary_user_task WHERE user_account_id = ? AND task_id = ?", accountId, task.getId());
        		if(BeanUtil.isNotEmpty(taskUser)) {
        			Integer evaluateAccountId = taskUser.getEvaluateAccountId();
            		//添加评价教师信息
            		if(taskUser.getEvaluateAccountId() != null){
    	                Record o = Redis.use().hget(Const.user.AccountIdInfo, evaluateAccountId);
    	                Admin admin = Redis.use().get(Const.user.Admin + o.getInt("id"));
    	                taskUser.put("teaName", admin.getName());
    	                taskUser.put("teaId", admin.getId());
    	                taskUser.put("teaAccountId", admin.getAccountId());
    	                taskUser.put("teaGender", admin.getGender());
    	                taskUser.put("teaPic", admin.getAvatarUrl());
            		}
            		task.put("taskUser", taskUser);
        		}
        	}
        	return Ret.ok("taskPage", taskPage);
    	}
    	return Ret.fail().set("error", EnumError.PARAMETER_ERROR.getObj());
    }

    /**
     *学生个人页面中查看学生已审核的任务
     */
    public Ret findUserTaskPage(Integer accountId, Integer page, Integer limit) throws Exception {
        Page<Record> taskUserPage = Db.paginate(page, limit, "SELECT * ", "FROM ordinary_user_task WHERE user_account_id = ? AND evaluate_account_id IS NOT NULL ORDER BY id DESC", accountId);
        List<Record> taskList = new ArrayList<Record>();
        for (Record ordinaryUserTask: taskUserPage.getList()) {
            OrdinaryTask ordinaryTask = OrdinaryTask.dao.findFirst("SELECT id,title,content,add_time FROM ordinary_task WHERE id = ?", ordinaryUserTask.getInt("task_id"));
            //添加评价教师信息
            if (ordinaryUserTask.getInt("evaluate_account_id") != null) {
                Record o = Redis.use().hget(Const.user.AccountIdInfo, ordinaryUserTask.getInt("evaluate_account_id"));
                Admin admin = Redis.use().get(Const.user.Admin + o.getInt("id"));
                ordinaryUserTask.put("teaName", admin.getName());
                ordinaryUserTask.put("teaId", admin.getId());
                ordinaryUserTask.put("teaAccountId", admin.getAccountId());
                ordinaryUserTask.put("teaGender", admin.getGender());
                ordinaryUserTask.put("teaPic", admin.getAvatarUrl());
            }
            ordinaryTask.put("taskUser", ordinaryUserTask);

            taskList.add(ordinaryTask.toRecord());
        }
        taskUserPage.setList(taskList);

        return Ret.ok("taskUserPage", taskUserPage);
    }

    /**
     * 提交任务
     */
    @Before(Tx.class)
    public Ret commitTask(Integer accountId, Integer taskId, String content, String files) throws Exception {
        //查询当前任务
        OrdinaryTask task = OrdinaryTask.dao.findById(taskId);
        if (BeanUtil.isEmpty(task) || task.getIsDel()) {
            return Ret.fail().set("error", EnumError.TASK_NOT_EXIST.getObj());
        }
        //查询当前用户有没有提交过该任务
        OrdinaryUserTask taskUser = OrdinaryUserTask.dao.findFirst("SELECT * FROM ordinary_user_task WHERE task_id = ? AND user_account_id = ?", taskId, accountId);
        if (BeanUtil.isNotEmpty(taskUser)) {
            return Ret.fail().set("error", EnumError.HAVE_COMPLETE_TASK.getObj());
        }
        OrdinaryUserTask ordinaryTaskUser = new OrdinaryUserTask();
        ordinaryTaskUser.setContent(content);
        ordinaryTaskUser.setTaskId(taskId);
        ordinaryTaskUser.setUserAccountId(accountId);
        ordinaryTaskUser.setFiles(files);
        ordinaryTaskUser.setTaskScore(task.getScore());
        ordinaryTaskUser.setTaskContent(task.getContent());
        ordinaryTaskUser.setTaskPictures(task.getPictures());
        ordinaryTaskUser.setTaskTitle(task.getTitle());
        ordinaryTaskUser.save();
        //创建taskLog,根据类型保存任务记录
        TaskLog taskLog = new TaskLog();
        taskLog.setTaskDate(LocalDateTime.now());
        taskLog.setTaskState(Const.taskState.UNAUDITED);
        taskLog.setUserAccountId(accountId);
        //设置任务类型
        taskLog.setTaskType(Const.taskType.ORDINARY_USER_TASK_TYPE);
        taskLog.setTaskId(ordinaryTaskUser.getId());
        taskLog.save();
        return Ret.ok();
    }
    
    /**
     * 查询任务详情
     */
    public Ret findTaskDetails(Integer accountId, Integer taskId) {
        OrdinaryTask ordinaryTask = OrdinaryTask.dao.findById(taskId);
        //添加审核老师信息
        if (ordinaryTask.getInt("evaluate_account_id") != null) {
            Integer teaAccountId = ordinaryTask.getInt("evaluate_account_id");
            Record o = Redis.use().hget(Const.user.AccountIdInfo, teaAccountId);
            Admin admin = Redis.use().get(Const.user.Admin + o.getInt("id"));
            ordinaryTask.put("teaName", admin.getName());
            ordinaryTask.put("teaId", admin.getId());
            ordinaryTask.put("teaAccountId", admin.getAccountId());
            ordinaryTask.put("teaGender", admin.getGender());
            ordinaryTask.put("teaPic", admin.getAvatarUrl());
        }
        OrdinaryUserTask ordinaryUserTask = OrdinaryUserTask.dao.findFirst("SELECT ut.*,(SELECT name FROM admin WHERE accountId = ut.evaluate_account_id) teaName FROM ordinary_user_task ut WHERE ut.task_id = ? AND ut.user_account_id = ?", taskId, accountId);
        
        return Ret.ok("ordinaryTask",ordinaryTask).set("ordinaryUserTask",ordinaryUserTask);
    }
    
    /**
     * 轨迹中查询普通任务详情
     * ps：轨迹和tasklog中普通任务存的是userTaskId
     */
    public Ret findTaskDetailsInTrajectory(Integer taskUserId) {
    	OrdinaryUserTask ordinaryUserTask = OrdinaryUserTask.dao.findFirst("SELECT ut.* FROM ordinary_user_task ut WHERE ut.id = ?", taskUserId);
    	if(BeanUtil.isEmpty(ordinaryUserTask)) {
    		return Ret.fail().set("error", EnumError.NOT_PAR_ACTIVITY.getObj());
    	}
    	//添加审核老师信息
        if (ordinaryUserTask.getInt("evaluate_account_id") != null) {
            Integer teaAccountId = ordinaryUserTask.getInt("evaluate_account_id");
            Record o = Redis.use().hget(Const.user.AccountIdInfo, teaAccountId);
            Admin admin = Redis.use().get(Const.user.Admin + o.getInt("id"));
            ordinaryUserTask.put("teaName", admin.getName());
            ordinaryUserTask.put("teaId", admin.getId());
            ordinaryUserTask.put("teaAccountId", admin.getAccountId());
            ordinaryUserTask.put("teaGender", admin.getGender());
            ordinaryUserTask.put("teaPic", admin.getAvatarUrl());
        }
    	OrdinaryTask ordinaryTask = OrdinaryTask.dao.findById(ordinaryUserTask.getTaskId());
    	
		return Ret.ok().set("ordinaryTask",ordinaryTask).set("ordinaryUserTask",ordinaryUserTask);
    }
    
    /**
     * 任务审核
     */
    public Ret examine(Integer accountId, Integer userType, Integer taskId, Integer score, String content, Boolean addTrajectory) throws Exception {
    	
    	//如果当前用户不是教师
        if (userType != Const.UserType.admin) {
            return Ret.fail().set("error", EnumError.ALLOW_ADMIN_EXAMINE.getObj());
        }
        OrdinaryUserTask ordinaryUserTask = OrdinaryUserTask.dao.findById(taskId);
        if (BeanUtil.isEmpty(ordinaryUserTask)) {
            return Ret.fail().set("error", EnumError.TASK_NOT_EXIST.getObj());
        }
        if (ordinaryUserTask.getState().intValue() == Const.taskState.REVIEWED) {
            return Ret.fail().set("error", EnumError.TASK_HAVA_EXAMINED.getObj());
        }
        //更新任务审核信息
        ordinaryUserTask.setScoreTeacher(score);
        ordinaryUserTask.setEvaluateTime(LocalDateTime.now());
        ordinaryUserTask.setEvaluateContent(content);
        ordinaryUserTask.setEvaluateAccountId(accountId);
        ordinaryUserTask.setState(Const.taskState.REVIEWED);
        ordinaryUserTask.setUpdateTime(LocalDateTime.now());
        ordinaryUserTask.update();
        //跟新任务记录
        TaskLog taskLog = TaskLog.dao.findFirst("SELECT * FROM task_log WHERE task_id = ? AND task_type = ?", taskId, Const.taskType.ORDINARY_USER_TASK_TYPE);
        taskLog.setTaskId(taskId);
        taskLog.setEvaluateAccountId(accountId);
        taskLog.setEvaluateTime(LocalDateTime.now());
        taskLog.setTaskState(Const.taskState.REVIEWED);
        taskLog.setUpdateTime(LocalDateTime.now());
        taskLog.update();
        //加入轨迹图
        if (score >= 3 && addTrajectory){
        	StudentTrajectory studentTrajectory = new StudentTrajectory();
            studentTrajectory.setTaskId(taskId);
            studentTrajectory.setTaskType(Const.taskType.ORDINARY_USER_TASK_TYPE);
            studentTrajectory.setUserAccountId(ordinaryUserTask.getUserAccountId());
            studentTrajectory.setContent(ordinaryUserTask.getContent());
            studentTrajectory.save();
        }
        //  给学生加分
        if (score > 0) {
            Record record = Redis.use().hget(Const.user.AccountIdInfo, ordinaryUserTask.getUserAccountId());
            UserUtil.addScoreForStu(record.getInt("id"), score, Const.addMarkEventType.ORDINARY_TASK, ordinaryUserTask.getId());
        }
        
        return Ret.ok();
    }
    

}
